package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.constants.AvatarMessageConstants;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.domain.business.BusDO;
import com.qk.domain.business.BusinessDO;
import com.qk.dto.business.BusDTO;
import com.qk.dto.business.BusinessDTO;
import com.qk.dto.business.UpdateBusinessDTO;
import com.qk.entity.Business;
import com.qk.entity.BusinessTrackRecord;
import com.qk.entity.Customer;
import com.qk.entity.User;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.BusinessTrackRecordMapper;
import com.qk.management.mapper.CustomerMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.BusinessService;
import com.qk.vo.business.BusinessVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BusinessTrackRecordMapper businessTrackRecordMapper;

    @Transactional
    @Override
    public void updateBusiness(UpdateBusinessDTO dto) {
        Business business = BeanUtil.copyProperties(dto, Business.class);
        business.setUpdateTime(LocalDateTime.now());
        if (dto.getStatus() == AvatarMessageConstants.WAIT_FOLLOW_UP) {
            business.setStatus(AvatarMessageConstants.FOLLOW_UP);
        }
        this.baseMapper.updateById(business);
        BusinessTrackRecord trackRecord = BeanUtil.copyProperties(dto, BusinessTrackRecord.class);
        trackRecord.setCreateTime(LocalDateTime.now());
        trackRecord.setBusinessId(null);
        trackRecord.setBusinessId(business.getId());
        trackRecord.setUserId(CurrentUserContextHolders.get());
        this.businessTrackRecordMapper.insert(trackRecord);
    }

    @Transactional
    @Override
    public BusinessVO getBusinessInfoById(Integer id) {
        Business bussiness = businessMapper.selectById(id);
        Integer userId = bussiness.getUserId();
        User user = userMapper.selectById(userId);
        List<BusinessTrackRecord> trackRecords = businessTrackRecordMapper
                .selectList(Wrappers.lambdaQuery(BusinessTrackRecord.class)
                        .in(BusinessTrackRecord::getBusinessId, id)
                );
        BusinessVO businessVO = BeanUtil.copyProperties(bussiness, BusinessVO.class);
        List<BusinessVO.BusinessTrackRecordvo> list = trackRecords.stream()
                .map(item -> {
                    BusinessVO.BusinessTrackRecordvo vo = BeanUtil.
                            copyProperties(item, BusinessVO.BusinessTrackRecordvo.class);
                    vo.setAssignName(user.getName());
                    return vo;
                }).toList();
        businessVO.setTrackRecords(list);
        return businessVO;
    }

    @Transactional
    @Override
    public void toBusiness(Integer id) {
        Business business = this.baseMapper.selectById(id);
        business.setStatus(AvatarMessageConstants.CONVERT_TO_CUSTOMER);
        business.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(business);
        Customer customer = BeanUtil.copyProperties(business, Customer.class);
        customer.setCreateTime(LocalDateTime.now());
        customer.setUpdateTime(LocalDateTime.now());
        customer.setBusinessId(id);
        this.customerMapper.insert(customer);
    }

    @Override
    public PageResult<BusDO> poollist(BusDTO bDTO) {
        PageHelper.startPage(bDTO.getPage(), bDTO.getPageSize());
        List<BusDO> result = businessMapper.selectPoolByPage(bDTO);
        Page<BusDO> page = (Page<BusDO>) result;
        return PageResult.<BusDO>builder()
                .total(Long.valueOf(result.size()))
                .rows(page.getResult())
                .build();
    }


    @Override
    public void add(Business business) {
        boolean hasnull = BeanUtil.hasNullField(business, "name",
                "phone", "channel"
        );
        if (!hasnull) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        businessMapper.insert(business);
    }

    @Override
    public PageResult<BusinessDO> list(BusinessDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<BusinessDO> result = businessMapper.selectByPage(dto);
        Page<BusinessDO> page = (Page<BusinessDO>) result;
        return PageResult.<BusinessDO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }
}